<?php
/**
 * 商品管理
 * @Author sunge
 * @DateTime  2019-06-19
 */
namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\Goods;
use App\Models\Order;
use App\Jobs\ExportData;
use \App\Models\GoodsHome;
use \App\Models\GoodsHomeRelation;
use \App\Models\GoodsEffectRelation;
use \App\Models\GlobalConfig;
use \App\Models\GoodsEffect;
use \App\Models\GoodsBrand;
use \App\Models\GoodsOrigin;
use \App\Models\GoodsNorm;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Services\UploadService;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\LayuiController as Layui;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;


class GoodsController extends Controller
{
    public $model;
    public $effectModel;
    public $homeModel;
    public $brandModel;
    public $originModel;
    public $normModel;


    public function __construct()
    {
        $this->model = new Goods();
        $this->effectModel = new GoodsEffect();
        $this->homeModel = new GoodsHome();
        $this->originModel = new GoodsOrigin();
        $this->brandModel = new GoodsBrand();
        $this->normModel = new GoodsNorm();
    }

    /**
     * 商品列表
     * @param $index
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getGoodsList($index)
    {
        $home =  $this->homeModel->getAll();
        $effect = $this->effectModel->getAll();
        return view('Admin/goods/index1',compact('home','effect','index'));
    }

    /**
     * 商品上下架设置 上下架 1下架  2上架
     */
    public function setStatus(Request $request, $id)
    {
        $data = $request->input('data');
        $status = $request->input('status');
        $data = explode(',', $data);
        \DB::beginTransaction();
        try{
            if($status == Goods::STATUS_OPEN or $status == Goods::SALE_STATUS_OUT){
                Goods::whereIn('id', $data )->update(['status' => Goods::STATUS_CLOSE]);
            }elseif($status == Goods::STATUS_CLOSE ){
                foreach($data as $key=>$value){
                    $stock = Goods::find($value)->stock;
                    if(empty($stock)){
                        \DB::rollBack();
                        return $this->getResponse('操作失败,库存数据必须大于0',[],201);
                    }
                }
                Goods::whereIn( 'id', $data )->update(['status' => Goods::STATUS_OPEN]);
            }

        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败' );
        }
        \DB::commit();
        return $this->getResponse('操作成功');
    }

    /**
     * 商品列表table 数据
     * @param Request $request
     * @param $id
     * @return array
     */
    public function table(Request $request,$id)
    {   $payload = $request->all(['keyword','is_sale','is_coupon','effect','module']);
        $goodsList = Goods::with(['orderGoods','goodsBrand','orderGoods.order'])->orderBy('sort','desc')
            ->when($keyword = array_get($payload,'keyword'),function($query)use($keyword){
                $query->where(function($query)use($keyword){
                    $query->whereHas('brandInfo', function ($query)use($keyword) {
                        $query->where('name', 'like', "%$keyword%");
                    })
                        ->orWhere('goods_name', 'like', "%$keyword%")
                        ->orWhere('title','like', "%$keyword%")
                        ->orWhere('sku','like', "%$keyword%");
                });

            })
            ->when($module = array_get($payload,'module'),function($query)use($module){
                $goodIdIN = GoodsHomeRelation::where('home_id',$module)->pluck('good_id');
                $query->whereIn('id',$goodIdIN);
            })
            ->when($effect = array_get($payload,'effect'),function($query)use($effect){
                $goodIdIN = GoodsEffectRelation::where('effect_id',$effect)->pluck('good_id');
                $query->whereIn('id',$goodIdIN);
            })
            ->when($id == Goods::SALE_STATUS_OPEN,function($query){
                $query->where('status', Goods::SALE_STATUS_OPEN)
                    ->where('stock','>', 0);
            })
            ->when($id == Goods::SALE_STATUS_CLOSE,function($query){//下架
                $query->where('status', Goods::SALE_STATUS_CLOSE);
            })
            ->when($id == Goods::SALE_STATUS_OUT,function($query){
                $query->where('stock', 0);
            })
            ->when($id == 4,function($query){ //价格查询
                $query->where('status', Goods::SALE_STATUS_OPEN);
            })
            ->when($is_sale = array_get($payload,'is_sale'),function($query)use($is_sale){ //价格查询
                $query->where('is_sale',$is_sale);
            })
            ->when($is_coupon = array_get($payload,'is_coupon'),function($query)use($is_coupon){ //价格查询
                $query->where('is_coupon',$is_coupon);
            })

            ->paginate($request->get('limit',10));
        $List = $goodsList->map(function($item)use($payload){
            $effect = "";
            $module = '';
            GoodsEffectRelation::where('good_id',$item->id)->pluck('effect_id');
            foreach(GoodsEffectRelation::where('good_id',$item->id)->pluck('effect_id') as $v){
                $effect .=  GoodsEffect::find($v)->name .",";
            }
            foreach(GoodsHomeRelation::where('good_id',$item->id)->pluck('home_id') as $v){
                $module .= GoodsHome::find($v)->module .",";

            }
            $effect = trim($effect,",");
            $module = trim($module,",");
            $filter = collect($item->orderGoods)->filter(function($value, $key) {
                if ($value->order->status == 5) {
                    return true;
                }
            });
            return [
                'id'         => $item->id,
                "goods_name" => $item->goods_name,
                "is_coupon" => $item->is_coupon,
                "is_sale" => $item->is_sale,
                "is_pay_balance" => $item->is_pay_balance,
                "sort" => $item->sort,
                "weight" => $item->weight,
                "title" => $item->title,
                "sku" => $item->sku,
                "price" => round($item->price,2),
                "stock" => $item->stock,
                "photo" => $item->photo,
                "brand" => $item->brand,
                "status" => $item->status,
                "order_goods" => $item->orderGoods ? :"",
                "goods_brand" => $item->goodsBrand ? $item->goodsBrand->name :"",
                "amount_sum"=>collect($filter)->sum('amount'),
                "effect"=>$effect,
                'module'=>$module
            ];
        });
        return Layui::tableJson($List,0,$goodsList->total());

    }

    /**
     * 添加商品
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|string
     * @throws FormException
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            $payload = $request->all([
                'goods_name',
                'title',
                'sku',
                'sort',
                'brand',
                'origin',
                'norm',
                'norm_unit',
                'effect',
                'price',
                'weight',
                'is_sale',
                'is_coupon',
                'is_pay_balance',
                'description',
                'photo',
                'banner'
                ]);
            Validator::make($payload, [
                'goods_name'     =>'required|unique:goods',
                'title'          =>'required|unique:goods',
                'sku'            =>'required|unique:goods',
                'sort'           =>'required',
                'brand'          =>'required',
                'origin'         =>'required',
                'norm'           =>'required',
                'norm_unit'      =>'required',
                'effect'         =>'required',
                'price'          =>'required|max:9999|min:0',
                'weight'         =>'required|integer',
                'is_sale'        =>'required',
                'is_coupon'      =>'required',
                'is_pay_balance' =>'required',
                'description'    =>'required',
                'photo'          =>'required',
            ],[
                'goods_name.required'     =>'请输入商品名称',
                'goods_name.unique'       =>'商品名称不唯一',
                'title.required'          =>'请输入商品简称',
                'title.unique'            =>'商品简称不唯一',
                'sku.required'            =>'请输入商品ID',
                'sku.unique'              =>'请输入唯一商品ID',
                'sort.required'           =>'请输入排序',
                'brand.required'          =>'请选择商品品牌',
                'origin.required'         =>'请选择商品产地',
                'norm.required'           =>'请输入单位数量',
                'norm_unit.required'      =>'请选择商品单位',
                'effect.required'         =>'请选择商品功效',
                'price.required'          =>'请输入商品价格',
                'price.max9999'           =>'商品价格大于最大值',
                'price.min0'              =>'商品价格必须大于0',
                'weight.required'         =>'请输入商品重量',
                'weight.integer'          =>'商品重量格式错误',
                'is_sale.required'        =>'请选择是否会员价',
                'is_coupon.required'      =>'请选择是否可用优惠券',
                'is_pay_balance.required' =>'请选择是否余额支付',
                'description.required'    =>'请输入商品描述',
                'photo.required'          =>'请上传商品图片',
            ])->validate();

            \DB::beginTransaction();
            try{
                if(!empty($payload['banner'])){
                    $banners = [];
                    foreach($payload['banner'] as $value){
                        $banners[] = $value;
                    }
                    $payload['banner'] = json_encode((object)$banners);
                }
                $payload['description'] = htmlentities($payload['description']);
                $effects = $payload['effect'];

                $effectsstr = ",";
                foreach($effects as $value){
                    $effectsstr .= $value.",";
                }
                $payload['effect'] = $effectsstr;
                $payload['created_at'] = date("Y-m-d H:i:s");
                $goods = Goods::create($payload);

                foreach($effects as $value){
                    GoodsEffectRelation::create(['effect_id' => $value,'good_id' => $goods->id]);
                }
            }catch (\Exception $exception){
                \DB::rollBack();
                throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            \DB::commit();
            return $this->getResponseSuccess('保存成功');
        } else {
            if (View::exists('Admin/goods/add')) {
                $effects = $this->effectModel->getAll();
                $brands = $this->brandModel->getAll();
                $homes = $this->homeModel->getAll();
                $origins = $this->originModel->getAll();
                $norms = $this->normModel->getAll();
                return view('Admin/goods/add',compact('effects','homes','brands','origins','norms'));
            } else {
                return 'View Not Found';
            }
        }
    }

    /**
     * 上传商品图片 产品缩略图,banner,textarea 图
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function uploadPhoto(Request $request)
    {
        if($request->hasFile('photo') ){//产品缩略图
            $UploadService = new UploadService($request,'goods','photo','oss');
//            $UploadService = new UploadService($request,'goods','photo','goods');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            return $this->getResponse( $msg = '上传成功', $data = [$uploadresult['url']]);

        } elseif($request->hasFile('banner')){
            $UploadService = new UploadService($request,'goods','banner','oss');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            return $this->getResponse( $msg = '上传成功', $data = [$uploadresult['url']]);

        } elseif($request->hasFile('file')){//textarea 图
            $UploadService = new UploadService($request,'goods','file','oss');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            return response()->json([
                'code'      => 0,
                'msg'       => '上传成功',
                'data'      => ['src'=>$uploadresult['url'],'title'=>""],
                'redirect'  => 'current'
            ]);
        }
        return $this->getResponse("图片上传失败");

    }

    /**
     * 设置商品配置信息图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function uploadConfig(Request $request)
    {
        if($request->hasFile('brand') ){
            $UploadService = new UploadService($request,'goodsconfig','brand','oss');
//            $UploadService = new UploadService($request,'goodsconfig','brand','goods');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            return $this->getResponse( $msg = '上传成功', $data = [$uploadresult['url']]);

        } elseif($request->hasFile('origin')){
            $UploadService = new UploadService($request,'goodsconfig','origin','oss');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            return $this->getResponse( $msg = '上传成功', $data = [$uploadresult['url']]);
        } elseif($request->hasFile('effect')){
            $UploadService = new UploadService($request,'goodsconfig','effect','oss');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            return $this->getResponse( $msg = '上传成功', $data = [$uploadresult['url']]);
        }

        return $this->getResponse("图片上传失败");

    }

    /**
     * 商品购买配置 上传图片 弹出框
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function uploadPage($id)
    {
        return view('Admin/goods/configUpload', compact('id'));
    }
    /**
     * 商品编辑页面 ,保存
     * @param Request $request
     * @param Goods $goods
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|string
     * @throws FormException
     */
    public function edit(Request $request,Goods $goods)
    {
        if ($request->isMethod('put')) {
            $payload = $request->all([
                'goods_name',
                'title',
                'sku',
                'sort',
                'brand',
                'origin',
                'norm',
                'norm_unit',
                'effect',
                'price',
                'weight',
                'is_sale',
                'is_coupon',
                'is_pay_balance',
                'description',
                'photo',
                'banner'
            ]);
            Validator::make($payload, [

                'goods_name'     =>'required',
                'title'          =>'required',
                'sku'            =>'required',
                'sort'           =>'required',
                'brand'          =>'required',
                'origin'         =>'required',
                'norm'           =>'required',
                'norm_unit'      =>'required',
                'effect'         =>'required',
                'price'          =>'required|max:9999|min:0',
                'weight'         =>'required|integer',
                'is_sale'        =>'required',
                'is_coupon'      =>'required',
                'is_pay_balance' =>'required',
                'description'    =>'required',
                'photo'          =>'required',
            ],[
                'goods_name.required'     =>'请输入商品名称',
                'title.required'          =>'请输入商品简称',
                'sku.required'            =>'请输入商品ID',
                'sort.required'           =>'请输入排序',
                'brand.required'          =>'请选择商品品牌',
                'origin.required'         =>'请选择商品产地',
                'norm.required'           =>'请输入单位数量',
                'norm_unit.required'      =>'请选择商品单位',
                'effect.required'         =>'请选择商品功效',
                'price.required'          =>'请输入商品价格',
                'price.max9999'           =>'商品价格大于最大值',
                'price.min0'              =>'商品价格必须大于0',
                'weight.required'         =>'请输入商品重量',
                'weight.integer'          =>'商品重量格式错误',
                'is_sale.required'        =>'请选择是否会员价',
                'is_coupon.required'      =>'请选择是否可用优惠券',
                'is_pay_balance.required' =>'请选择是否余额支付',
                'description.required'    =>'请输入商品描述',
                'photo.required'          =>'请上传商品图片',

            ])->validate();
            DB::beginTransaction();
            try{
                GoodsEffectRelation::where('good_id', $goods->id)->delete();
                $effectsstr = ",";
                foreach($payload['effect'] as $value){
                    GoodsEffectRelation::create(['effect_id' => $value,'good_id' => $goods->id]);
                    $effectsstr .= $value.",";
                }
                if(!empty($payload['banner'])){
                    $banners = [];
                    foreach($payload['banner'] as $value){
                        $banners[] = $value;
                    }
                    $payload['banner'] = json_encode((object)$banners);
                }
                $payload['effect'] = $effectsstr;
                $payload['description'] = htmlentities($payload['description']);
                $payload['updated_at'] = date("Y-m-d H:i:s");
                $goods->update($payload);

            }catch (\Exception $exception){
                DB::rollBack();
                throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            DB::commit();
            return $this->getResponse('保存成功');
        } else {

            if (View::exists('Admin/goods/edit')) {
                $effects = $this->effectModel->getAll();
                $brands = $this->brandModel->getAll();
                $homes = $this->homeModel->getAll();
                $origins = $this->originModel->getAll();
                $norms = $this->normModel->getAll();
                $goodeffects = GoodsEffectRelation::where('good_id',$goods->id)->pluck('effect_id')->toArray();
                return view('Admin/goods/edit', compact('goods','effects','homes','brands','origins','norms','goodeffects'));
            } else {
                return 'View Not Found';
            }
        }
    }

    /**
     * 删除商品
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws FormException
     */
    public function delete(Request $request)
    {
        $id = $request->input("id");
        \DB::beginTransaction();
        try{
            Goods::destroy($id);
        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '删除失败' );
        }
        \DB::commit();
        return $this->getResponse('删除成功');
    }

    public function upsort(Request $request){
        $value = $request->input("value");
        $id = $request->input("id");
        \DB::beginTransaction();
        try{
            $model = Goods::findOrFail($id);
            $model->sort=$value;
            $model->save();
        }catch (\Exception $exception){
            \DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '更新失败' );
        }
        \DB::commit();
        return $this->getResponse('更新成功');
    }
    /**
     * 商品购买配置
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     * @throws FormException
     */
    public function buyset(Request $request)
    {
        if ($request->isMethod('put')) {
            $payload = $request->all([
                'num',
            ]);
            Validator::make($payload, [
                'num' =>'required|min:0',
            ],[
                'num.required'  =>'请输入单件商品单次最大购买数量',
                'num.min:0'     =>'数量不能小于0',
            ])->validate();
            DB::beginTransaction();
            try{
                GlobalConfig::where('code','goods_buy_up_limit')->update(['value'=>$payload['num']]);
            }catch (\Exception $exception){
                DB::rollBack();
                throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            DB::commit();
            return $this->getResponse('保存成功');
        }else{
            $num = GlobalConfig::where('code','goods_buy_up_limit')->first()->value;
            return view('Admin/goods/buyset', compact('num'));
        }
    }

    /**
     * 商品购买配置 添加属性 品牌,产地,功效,规格
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|string
     * @throws FormException
     */
    public function config(Request $request)
    {
        if ($request->isMethod('post')) {
            $name = $request->input('name');
            $photo = $request->input('photo');
            $id = $request->input('id');
            DB::beginTransaction();
            try{
                if($id ==1){
                    GoodsBrand::create(['name'=>$name,'photo'=>$photo]);
                }elseif($id==2){
                    GoodsOrigin::create(['name'=>$name,'photo'=>$photo]);
                }elseif($id==3){
                    GoodsEffect::create(['name'=>$name,'photo'=>$photo]);
                }elseif($id ==4){
                    GoodsNorm::create(['name'=>$name]);
                }elseif($id==5){ //brand
                    $banner = Banner::FindOrFail(14);
                    $banner->photo = $photo;
                    $banner->updated_at = date("Y-m-d H:i:s");
                    $banner->save();
                }elseif($id==6){//Origin16
                    $banner = Banner::FindOrFail(16);
                    $banner->photo = $photo;
                    $banner->updated_at = date("Y-m-d H:i:s");
                    $banner->save();
                }elseif($id ==7){//Effect15
                    $banner = Banner::FindOrFail(15);
                    $banner->photo = $photo;
                    $banner->updated_at = date("Y-m-d H:i:s");
                    $banner->save();
                }
            }catch (\Exception $exception){
                DB::rollBack();
                throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
            }
            DB::commit();
            return $this->getResponse('保存成功');


        }else{
            if (View::exists('Admin/goods/config')) {
                $effects = $this->effectModel->getAll();
                $brands = $this->brandModel->getAll();
                $homes = $this->homeModel->getAll();
                $origins = $this->originModel->getAll();
                $norms = $this->normModel->getAll();
                $brandurl = Banner::where("id",14)->first()->photo;
                $originurl = Banner::where("id",16)->first()->photo;
                $effecturl = Banner::where("id",15)->first()->photo;
                return view('Admin/goods/config',compact('effects','homes','brands','origins','norms','brandurl','originurl','effecturl'));
            } else {
                return 'View Not Found';
            }


        }
    }

    /**
     * 商品购买配置 删除属性 品牌,产地,功效,规格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws FormException
     */
    public function configdel(Request $request)
    {
        $id = $request->input('id');
        $type = $request->input("type");

        DB::beginTransaction();
        try{
            if($type == 1){
                GoodsBrand::where('id', $id)->update(["status"=>2]);
            }elseif($type==2){
                GoodsOrigin::where('id', $id)->update(["status"=>2]);
            }elseif($type==3){
                GoodsEffect::where('id', $id)->update(["status"=>2]);
            }elseif($type==4){
                GoodsNorm::where('id', $id)->update(["status"=>2]);
            }
        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');

    }

    /**
     * 更新商品基本信息管理 文字内容
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws FormException
     */
    public function configchange(Request $request)
    {
        $id = $request->input('id');
        $type = $request->input("type");
        $value = $request->input("value");

        DB::beginTransaction();
        try{
            if($type == 1){
                GoodsBrand::where('id', $id)->update(["name"=>$value]);
            }elseif($type==2){
                GoodsOrigin::where('id', $id)->update(["name"=>$value]);
            }elseif($type==3){
                GoodsEffect::where('id', $id)->update(["name"=>$value]);
            }elseif($type==4){
                GoodsNorm::where('id', $id)->update(["name"=>$value]);
            }
        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');
    }

    /**
     * 商品列表页导出excel
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function export(Request $request)
    {
        $payload = $request->all();
        $filename = $request->input('filename','demo.csv');
        $filename = rtrim($filename,'.csv').'.csv';
        $id =$payload['id'];
        if(Storage::disk('exports')->exists($filename))
            return $this->getResponse('文件已存在，请重新输入',[],302,url('admin/user/index'));
        //判断前台是否有选择
        if(empty($payload['ids'])){
            /* 获取查询条件 */
            $payload = $request->all();
            $preData = Goods::with(['orderGoods','goodsBrand'])->orderBy('sort','desc')
                ->when($keywords = array_get($payload,'keywords'),function($query)use($keywords){
                    $query->where(function($query)use($keywords){
                        $query->whereHas('brandInfo', function ($query)use($keywords) {
                            $query->where('name', 'like', "%$keywords%");
                        })
                            ->orWhere('goods_name', 'like', "%$keywords%")
                            ->orWhere('title','like', "%$keywords%")
                            ->orWhere('sku','like', "%$keywords%");
                    });
                })
                ->when($module = array_get($payload,'module'),function($query)use($module){
                    $goodIdIN = GoodsHomeRelation::where('home_id',$module)->pluck('good_id');
                    $query->whereIn('id',$goodIdIN);
                })
                ->when($effect = array_get($payload,'effect'),function($query)use($effect){
                    $goodIdIN = GoodsEffectRelation::where('effect_id',$effect)->pluck('good_id');
                    $query->whereIn('id',$goodIdIN);
                })
                ->when($id == Goods::SALE_STATUS_OPEN,function($query){
                    $query->where('status', Goods::SALE_STATUS_OPEN)
                        ->where('stock','>', 0);
                })
                ->when($id == Goods::SALE_STATUS_CLOSE,function($query){//下架
                    $query->where('status', Goods::SALE_STATUS_CLOSE);
                })
                ->when($id == Goods::SALE_STATUS_OUT,function($query){
                    $query->where('stock', 0);
                })
                ->when($id == 4,function($query){ //价格查询
                    $query->where('status', Goods::SALE_STATUS_OPEN);
                })
                ->when($is_sale = array_get($payload,'is_sale'),function($query)use($is_sale){ //价格查询
                    $query->where('is_sale',$is_sale);
                })
                ->when($is_coupon = array_get($payload,'is_coupon'),function($query)use($is_coupon){ //价格查询
                    $query->where('is_coupon',$is_coupon);
                })

                ->get();

        }else{
            //有选择
            $ids = explode(',',$payload['ids']);
            $preData = Goods::with(['orderGoods','goodsBrand'])
                ->whereIn( 'id', $ids)
                ->orderBy('sort','desc')
                ->get();
        };
        if( count($preData) == 0 ){
            return $this->getResponse('导出不能为空，请重新尝试',[],302,url('admin/user/index'));
        }
        $preData = $preData->map(function($item)use($payload){
            $effect = "";
            $module = '';
            foreach(GoodsEffectRelation::where('good_id',$item->id)->pluck('effect_id') as $v){
                $effect .= GoodsEffect::find($v)->name .",";
            }
            foreach(GoodsHomeRelation::where('good_id',$item->id)->pluck('home_id') as $v){
                $module .= GoodsHome::find($v)->module .",";
            }
            $item->effect = trim($effect,",");
            $item->module = trim($module,",");
            $item->brand = GoodsBrand::find($item->brand)->name;
            $item->is_sale = Goods::IS_SALE[$item->is_sale];
            $item->is_coupon = Goods::IS_COUPON[$item->is_coupon];
            $item->is_pay_balance = Goods::IS_PAY_BALANCE[$item->is_pay_balance];
            $item->amount_sum = collect($item->orderGoods)->sum('amount');
            return $item;
        });

        /* 定义文件头 */
        $header = [
            'sort'     => '排序',
            'title'      => '商品简称',
            'goods_name' => '商品名称',
            'sku' => '商品编码',
            'brand' => '商品品牌',
            'weight' => '商品质量',
            'price' => '销售价格',
            'is_sale' => '会员价属性',
            'is_coupon' => '优惠券属性',
            'is_pay_balance' => '支付属性',
            'stock' => '库存',
            'amount_sum' => '销量',
            'module' => '所属模块',
            'effect' => '功效',
        ];

        /* 插入队列 */
        /* 闭包序列化处理 */
        //$serializer = new Serializer();
        dispatch(new ExportData($header,'','',$filename,$preData->toArray()));
        return $this->getResponse('已加入导出队列',[],200,url('admin/partner'));
    }

}